#pragma once

#include <iostream>
#include <string>
#include <cstdio>
#include <vector>
class Command
{
private:
    bool IsSafe(const std::string &cmd)
    {
        for(auto &e : _safe_command)
        {
            if(e == cmd)
                return true;
        }
        return false;
    }

public:
    Command()
    {
        // 课堂上，只允许少量命令的执⾏，限定⼀下命令的个数和范围
        _safe_command.push_back("ls");
        _safe_command.push_back("pwd");
        _safe_command.push_back("ls -l");
        _safe_command.push_back("ll");
        _safe_command.push_back("touch");
        _safe_command.push_back("who");
        _safe_command.push_back("whoami");
    }
    std::string Exec(const std::string cmd)
    {
        if(!IsSafe(cmd))
        {
            return "无效命令";
        }
        std::string result;
        FILE *fp = popen(cmd.c_str(), "r");
        if (fp == NULL)
        {
            result = cmd + " Exec error";
        }
        else
        {
            char buffer[1024];
            while (fgets(buffer, sizeof(buffer), fp) != nullptr)
            {
                result += buffer;
            }
            pclose(fp);
        }
        return result;
    }
    ~Command()
    {
    }

private:
    std::vector<std::string> _safe_command;
};